package com.example.apkmanage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.example.apkmanage.adapter.MainListViewAdapter;
import com.example.apkmanage.adapter.ResponseCacheManager;
import com.example.apkmanage.base.BaseActivity;
import com.ta.annotation.TAInject;
import com.ta.annotation.TAInjectView;
import com.ta.util.cache.TAFileCacheWork;
import com.ta.util.http.AsyncHttpClient;
import com.ta.util.http.AsyncHttpResponseHandler;

public class MainActivity extends BaseActivity {
	private ListView mListView;
	private JSONArray jsonList = new JSONArray();

	private AlertDialog showApkInfo;
	private MainListViewAdapter mainListViewAdapter;
	String newVerName = "";// 新版本名称
	int newVerCode = -1;// 新版本号
	ProgressDialog pd = null;
	String UPDATE_SERVERAPK = "APKManage.apk";

	private TAFileCacheWork<JSONObject> taFileCacheWork;

	@TAInject
	private AsyncHttpClient asyncHttpClient;

	@TAInjectView(id = R.id.ivTitleBtnRigh)
	private ImageButton rightButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

	}

	@Override
	protected void onAfterSetContentView() {
		// TODO Auto-generated method stub
		super.onAfterSetContentView();
		OnClickListener onClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.ivTitleBtnRigh:
					Refresh();
					break;
				default:
					break;
				}
			}
		};
		rightButton.setOnClickListener(onClickListener);

	}

	private void initListDate() {

		try {
			JSONObject jsonObj = new JSONObject(ResponseCacheManager.getInstance().getResponse(MAIN_JSON_CACHE).toString());
			jsonList = jsonObj.getJSONArray("info");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		mainListViewAdapter = new MainListViewAdapter(this, jsonList, downLoadOnClickListener, mListView);
		mListView = (ListView) this.findViewById(R.id.listview);
		mListView.setAdapter(mainListViewAdapter);
		mListView.setOnItemClickListener(mylistviewOnItemClickListener);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Refresh();
	}

	private void Refresh() {
		asyncHttpClient.get(THINKANDROIDURL + "getsoft.service", new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				RefreshDate(content);
				super.onSuccess(content);
			}
		});
	}

	private void RefreshDate(String content) {
		try {
			if (StringUtils.isNotEmpty(content)) {
				ResponseCacheManager.getInstance().putResponse(MAIN_JSON_CACHE, content);
			}
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "服务器忙。请稍候", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		} finally {
			initListDate();
		}

	}

	/**
	 * �б���
	 */
	private OnItemClickListener mylistviewOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			showAPKInfo();
		}
	};
	/**
	 * ��ť���
	 */
	private OnClickListener downLoadOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// if (v == MainListViewHolder.imgDownLoad) {
			//
			// }
			Toast.makeText(getApplicationContext(), "tem", Toast.LENGTH_SHORT).show();
		}
	};

	private void showAPKInfo() {
		showApkInfo = new AlertDialog.Builder(this).create();
		showApkInfo.setTitle("提示");// 设置标题
		showApkInfo.setMessage("而 Holo Theme 最大的特点是什么？简单，质朴。Google 提供的 Holo 控件是不可能违背 Android Design 的，而这些控件的样式和配色也非常保守，不会影响用户的操作或者分散用户的注意力，Holo Theme 的布局也是最为普通的列表。而 Android 系统对这些默认元素的优化已经很到位了，所以就算是默认的 Holo 主题也能带来不错的阅读/操作体验");
		showApkInfo.setIcon(R.drawable.icon_360);// 设置图标
		showApkInfo.setCancelable(true);// 设置进度条是否可以按退回键取消
		showApkInfo.setCanceledOnTouchOutside(true);
		showApkInfo.show();
	}

	private void showAbout() {
		showApkInfo = new AlertDialog.Builder(this).create();
		showApkInfo.setTitle("版本管理器");// 设置标题
		showApkInfo.setMessage("XXX");
		showApkInfo.setIcon(R.drawable.ic_launcher);// 设置图标
		showApkInfo.setCancelable(true);// 设置进度条是否可以按退回键取消
		showApkInfo.setCanceledOnTouchOutside(true);
		showApkInfo.show();
	}

	private Menu mainmenu;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		mainmenu = menu;
		mainmenu.add(0, 1, Menu.NONE, "全部暂停").setIcon(R.drawable.menu_redownload);
		mainmenu.add(0, 2, Menu.NONE, "全部更新").setIcon(R.drawable.menu_downmanager);
		mainmenu.add(0, 3, Menu.NONE, "版本检测").setIcon(R.drawable.menu_normalmode);
		mainmenu.add(1, 4, Menu.NONE, "退出").setIcon(R.drawable.menu_quit);
		mainmenu.add(1, 5, Menu.NONE, "刷新").setIcon(R.drawable.menu_bookmark_sync_sync);
		mainmenu.add(1, 6, Menu.NONE, "关于").setIcon(R.drawable.menu_about);

		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * ʵ�ֲ˵���Ϊ
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		setTitle(item.getItemId() + item.getTitle().toString());
		switch (item.getItemId()) {
		case 3:
			validateVesion();
			return true;
		case 4:
			exitdialog();
			return true;
		case 5:
			Refresh();
			return true;
		case 6:
			showAbout();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void validateVesion() {
		asyncHttpClient.get(THINKANDROIDURL + "getsys.service", new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				// TODO Auto-generated method stub
				alrt(content);
				super.onSuccess(content);
			}
		});
	}

	/**
	 * 版本更新
	 * 
	 * @param content
	 */
	public void alrt(String content) {

		try {
			JSONObject jsonObj = new JSONObject(content);
			JSONObject info = jsonObj.getJSONObject("info");
			if (getVesion(info.getString("vnum")) > getVesion(getVerName(this))) {
				doNewVersionUpdate(info.getString("vpath"));// 更新版本
			} else {
				notNewVersionUpdate();// 提示已是最新版本
			}

		} catch (JSONException e) {
			Toast.makeText(getApplicationContext(), "服务器忙。请稍候", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}

	/**
	 * 获得版本号
	 */
	public int getVerCode(Context context) {
		int verCode = -1;
		try {
			verCode = context.getPackageManager().getPackageInfo("com.example.apkmanage", 0).versionCode;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e("版本号获取异常", e.getMessage());
		}
		return verCode;
	}

	/**
	 * 获得版本名称
	 */
	public String getVerName(Context context) {
		String verName = "";
		try {
			verName = context.getPackageManager().getPackageInfo("com.example.apkmanage", 0).versionName;
		} catch (NameNotFoundException e) {
			Log.e("版本名称获取异常", e.getMessage());
		}
		return verName;
	}

	/**
	 * 不更新版本
	 */
	public void notNewVersionUpdate() {
		int verCode = this.getVerCode(this);
		String verName = this.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本：");
		sb.append(verName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append("\n已是最新版本，无需更新");
		Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新").setMessage(sb.toString()).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// finish();
			}
		}).create();
		dialog.show();
	}

	/**
	 * 更新版本
	 */
	public void doNewVersionUpdate(final String apkurl) {
		int verCode = this.getVerCode(this);
		String verName = this.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本：");
		sb.append(verName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append(",发现版本：");
		sb.append(newVerName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append(",是否更新");

		Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新").setMessage(sb.toString()).setPositiveButton("更新", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				pd = new ProgressDialog(MainActivity.this);
				pd.setTitle("正在下载");
				pd.setMessage("请稍后。。。");
				pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				downFile(apkurl);
			}
		}).setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				// finish();
			}
		}).create();
		// 显示更新框
		dialog.show();
	}

	/**
	 * 下载apk
	 */
	public void downFile(final String url) {
		pd.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK);
						fileOutputStream = new FileOutputStream(file);
						byte[] b = new byte[1024];
						int charb = -1;
						int count = 0;
						while ((charb = is.read(b)) != -1) {
							fileOutputStream.write(b, 0, charb);
							count += charb;
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			super.handleMessage(msg);
			pd.cancel();
			update();
		}
	};

	/**
	 * 下载完成，通过handler将下载对话框取消
	 */
	public void down() {
		new Thread() {
			public void run() {
				Message message = handler.obtainMessage();
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 安装应用
	 */
	public void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), UPDATE_SERVERAPK)), "application/vnd.android.package-archive");
		startActivity(intent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { // ���/9��/�qη��ؼ�
			exitdialog();
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			// ���/9�ز˵���
		} else if (keyCode == KeyEvent.KEYCODE_HOME) {
			// ����Home��Ϊϵͳ��˴����ܲ�����Ҫ��дonAttachedToWindow()
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void exitdialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("是否要退出？");

		builder.setTitle("提示ʾ");

		builder.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				MainActivity.this.finish();
			}
		});

		builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.create().show();
	}

}
